<template>
  <el-dialog :visible.sync="currentVisible"
             append-to-body
             destroy-on-close
             :close-on-click-modal="false"
             :title="$t('custom.bots.all_message_switch')"
             custom-class="turn-modal"
             width="380px">

    <div class="turn-modal-content"
         v-loading="loading">
      <div class="turn-modal-content-header">
        Caution:
      </div>
      <div class="turn-modal-content-desc">
        Turning off this switch will disable all the bots' messages from being sent out to users.
        This is used for troubleshooting if you receive a large number of wrong messages.
        If you only want to turn off certain bots messages, please turn off the enable switch for each bot message.
        If you only need to turn off messages for certain users,
        please go to Settings > User Management > Action to turn off the message switch for specific users.
      </div>

      <div class="z-modal-footer">
        <el-button type="primary"
                   size="small"
                   @click="onCancel">{{ $t('cancel') }}</el-button>
        <el-button type="danger"
                   @click="onConfirm"
                   size="small">{{ $t('custom.bots.confirm') }}</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { setSetting } from '@/api/new'
import useErrorMessage from '@/components/storybook/hooks/useErrorMessage'

export default {
  name: 'TurnModal',
  props: {
    visible: Boolean,
    form: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      loading: false,

    }
  },
  computed: {
    currentVisible: {
      get () {
        return this.visible
      },
      set (val) {
        this.$emit('update:visible', val)
      }
    }
  },

  methods: {
    onCancel () {
      this.currentVisible = false
      this.$emit('cancel')
    },
    async onConfirm () {
      if (!this.$store.state.user.email) {
        return this.$message.error(this.$t('custom.bots.updateBotsMessage'))
      }

      try {
        this.loading = true
        const { keyword, value, ...rest } = this.form
        const params = {
          ...rest,
          keyword,
          value: 'false',
          email: this.$store.state.user.email
        }
        const { data: response } = await setSetting(params)
        if (response.code !== 0) {
          throw response.msg
        }

        this.$message.success(response.msg)
        this.currentVisible = false
        this.$emit('success', response.data || {})
      } catch (error) {
        useErrorMessage(error)
      } finally {
        this.loading = false
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.turn-modal {
  &-content {
    &-header {
      color: red;
      font-size: 20px;
      margin-bottom: 10px;
    }
    &-desc {
      padding: 0 10px;
      word-break: break-word;
      white-space: normal;
      line-height: 20px;
    }
  }
}
</style>